import { Button, Form, message } from 'antd';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import type { FormCategoryType } from '@/pages/Category/data';
import { updateCategory } from '../service';
const formLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
interface UpdateFormProps {
  setRefreshCount: any;
  formVals: FormCategoryType;
}
const UpdateModalForm = (props: UpdateFormProps) => {
  const { formVals, setRefreshCount } = props;
  const [form] = Form.useForm();
  /**
   * 更新节点
   * @param fields
   */
  const handleUpdate = async (fields: FormCategoryType) => {
    const hide = message.loading('正在更新');
    try {
      const res = await updateCategory({
        ...fields,
        id: formVals.id,
        user_id: formVals.user_id,
      });
      hide();
      if (res.success) {
        setRefreshCount((count: any) => count + 1);
        message.success('更新成功');
      } else {
        message.error('更新失败,请重试');
      }
      return true;
    } catch (error) {
      hide();
      message.error('更新失败,请重试');
      return false;
    }
  };
  return (
    <ModalForm
      form={form}
      layout="horizontal"
      {...formLayout}
      title="编辑分类"
      modalProps={{
        onCancel: () => form.resetFields(),
      }}
      initialValues={{
        name: formVals.name,
      }}
      trigger={
        <Button size="small" type="primary">
          编辑
        </Button>
      }
      onFinish={async () => {
        form
          .validateFields()
          .then((fieldsValue) => {
            handleUpdate(fieldsValue);
          })
          .catch(() => {});
        return true;
      }}
    >
      <ProFormText
        width={256}
        key="name"
        name="name"
        label="分类名"
        rules={[{ required: true, message: '请输入分类名' }]}
      />
    </ModalForm>
  );
};
export default UpdateModalForm;
